<template>
	<!-- 头部navbar -->
	<view class="content-box">
		<navbar :fixed="true" :bgColor="'#fff'" :title="t('position.cc')" :leftIcon="true"></navbar>
		<!-- 持仓类型切换 -->
		<view class="position-tabs">
			<view class="border-box">
				<view class="tab-item" :class="{ active: activeTab === 'current' }" @click="switchTab('current')">
					{{ t('position.dqcc') }}
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'history' }" @click="switchTab('history')">
					{{ t('position.lscc') }}
				</view>
			</view>
		</view>

		<!-- 持仓列表 -->
		<view class="position-list">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 当前持仓 -->
			<template v-else-if="activeTab === 'current'">
				<!-- 空数据状态 -->
				<view v-if="currentPositions.length === 0" class="empty-container">
					<text class="empty-text">暂无当前持仓</text>
				</view>
				<!-- 持仓列表 -->
				<view v-else class="position-item" v-for="(item, index) in currentPositions" :key="index" @click="goDetails(item)">
					<view class="position-header">
						<view class="symbol-info">
							<text class="symbol">{{ item.symbol }}</text>
							<view class="direction-tag" :class="item.direction === 'up' ? 'up' : item.direction === 'down' ? 'down' : 'ping'">
								<image :src="item.direction === 'up' ? '/static/icon/up-icon2.svg' : item.direction === 'down' ? '/static/icon/down-icon2.svg' : '/static/image/postion/ping.svg'"
									mode="aspectFit"></image>
							</view>
						</view>
						<view class="right">
							<view class="progress-bar">
								<view class="progress-fill" :style="{ width: item.progressWidth }"></view>
							</view>
							<view class="time-info">
								<text>{{ item.progressTime }}</text>
							</view>
						</view>
					</view>
					<view class="position-details">
						<view class="detail-column">
							<text class="label">{{ t('position.kyjg') }}</text>
							<text class="value">{{ item.openPrice }}</text>
						</view>
						<view class="detail-column">
							<text class="label">{{ t('position.xdsl') }}</text>
							<text class="value">{{ item.amount }}</text>
						</view>
						<view class="detail-column">
							<text class="label">{{ t('position.syl') }}</text>
							<text class="value"
								:class="item.profitRatio > 0 ? 'profit' : item.profitRatio < 0 ? 'loss' : 'ping'">{{ item.profitRatio }}%</text>
						</view>
						<view class="detail-column">
							<text class="label">{{ t('position.fdsy') }}</text>
							<text class="value"
								:class="item.floatingProfit.startsWith('+') ? 'profit' : item.floatingProfit.startsWith('0') ? 'ping' : 'loss'">{{ item.floatingProfit }}</text>
						</view>
						<view class="detail-column">
							<text class="label">订单状态</text>
							<text class="value status" :class="'status-' + item.statusCode">{{ item.status }}</text>
						</view>
					</view>

				</view>
			</template>

			<!-- 历史持仓 -->
			<template v-else>
				<!-- 空数据状态 -->
				<view v-if="historyPositions.length === 0" class="empty-container">
					<text class="empty-text">暂无历史持仓</text>
				</view>
				<!-- 持仓列表 -->
				<view v-else class="position-item" @click="goDetails(item)" v-for="(item, index) in historyPositions" :key="index">
					<view class="position-header">
						<view class="symbol-info">
							<text class="symbol">{{ item.symbol }}</text>
							<view class="direction-tag"
								:class="item.direction === 'up' ? 'up' :item.direction ===  'down'?'down': 'ping'">
								<image
									:src="item.direction === 'up' ? '/static/icon/up-icon2.svg' :item.direction === 'down'?'/static/icon/down-icon2.svg':'/static/image/postion/ping.svg'"
									mode="aspectFit"></image>
							</view>
						</view>
						<view class="right">
							<view class="progress-bar">
								<view class="progress-fill" :style="{ width: item.progressWidth }"></view>
							</view>
							<view class="time-info">
								<!-- <text>{{ item.time }}</text> -->
								<text>{{item.progressTime}}</text>
							</view>
						</view>
					</view>
					<view class="position-details">
						<view class="detail-column">
							<text class="label">{{ t('position.kyjg') }}</text>
							<text class="value">{{ item.openPrice }}</text>
						</view>
						<view class="detail-column">
							<text class="label">{{ t('position.xdsl') }}</text>
							<text class="value">{{ item.amount }}</text>
						</view>
						<view class="detail-column">
							<text class="label">{{ t('position.syl') }}</text>
							<text class="value"
								:class="item.profitRatio > 0 ? 'profit' : item.profitRatio < 0 ? 'loss' : 'ping'">{{ item.profitRatio }}%</text>
						</view>
						<view class="detail-column">
							<text class="label">{{ t('position.fdsy') }}</text>
							<text class="value"
								:class="item.floatingProfit.startsWith('+') ? 'profit' :item.profitRate.startsWith('0')?'ping':'loss'">{{ item.floatingProfit }}</text>
						</view>
					</view>
					<!-- 					<view class="position-progress">
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: item.progressWidth }"></view>
						</view>
						<text class="progress-time">{{ item.progressTime }}</text>
					</view> -->
				</view>
			</template>
		</view>

		<!-- 底部tabbar -->
		<tabbar :currentTab="3"></tabbar>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		useI18n
	} from 'vue-i18n';
	import { optionApi } from '@/utils/api.js';
	
	const {
		t,
		locale
	} = useI18n();

	// 当前选中的标签
	const activeTab = ref('current');
	
	// 加载状态
	const loading = ref(false);
	
	// 分页参数
	const pageParams = ref({
		pageNo: 1,
		pageSize: 20
	});

	// 切换标签
	const switchTab = (tab) => {
		activeTab.value = tab;
		// 切换标签时重新加载数据
		loadPositionData();
	};
	
	// 格式化数字
	const formatNumber = (value) => {
		if (value === null || value === undefined) return '0';
		return Number(value).toFixed(2);
	};
	
	// 格式化百分比
	const formatPercent = (value) => {
		if (value === null || value === undefined) return '0%';
		const num = Number(value);
		const sign = num > 0 ? '+' : num < 0 ? '' : '';
		return `${sign}${(num * 100).toFixed(2)}%`;
	};
	
	// 格式化收益
	const formatProfit = (value) => {
		if (value === null || value === undefined) return '0';
		const num = Number(value);
		const sign = num > 0 ? '+' : num < 0 ? '' : '';
		return `${sign}${num.toFixed(2)}`;
	};
	
	// 获取订单状态文本
	const getStatusText = (status) => {
		const statusMap = {
			0: '待结算',
			1: '盈利',
			2: '亏损',
			3: '平局'
		};
		return statusMap[status] || '未知';
	};
	
	// 获取方向文本
	const getDirectionText = (direction) => {
		return direction === 1 ? 'up' : direction === 2 ? 'down' : 'ping';
	};
	
	// 转换API数据为模板所需格式
	const transformOrderData = (apiData) => {
		return apiData.map(item => ({
			id: item.id,
			symbol: item.productName || 'Unknown', // 币种名称
			direction: getDirectionText(item.direction), // 方向
			openPrice: formatNumber(item.buyPrice), // 开仓价格
			amount: formatNumber(item.amount), // 下单额
			profitRate: formatPercent(item.profitRatio), // 格式化后的收益率
			profitRatio: item.profitRatio, // 原始收益率数值
			floatingProfit: formatProfit(item.profit), // 浮动收益
			status: getStatusText(item.status), // 订单状态
			statusCode: item.status, // 原始状态码
			time: item.createTime,
			progressWidth: item.status === 0 ? '50%' : '100%', // 待结算显示50%，已结算显示100%
			progressTime: item.status === 0 ? '进行中' : '结束'
		}));
	};

	// 加载持仓数据
	const loadPositionData = async () => {
		try {
			loading.value = true;
			const status = activeTab.value === 'current' ? 0 : 1; // 0为当前持仓，1为历史持仓
			
			const params = {
				...pageParams.value,
				status
			};
			
			const response = await optionApi.getOrderPage(params);
			
			if (response && response.code === 0) {
				const data = response.data || {};
				const list = data.list || [];
				
				// 转换数据格式
				const transformedData = transformOrderData(list);
				
				if (activeTab.value === 'current') {
					currentPositions.value = transformedData;
				} else {
					historyPositions.value = transformedData;
				}
			} else {
				uni.showToast({
					title: response?.msg || '获取数据失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('加载持仓数据失败:', error);
			uni.showToast({
				title: '网络错误，请稍后重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};

	// 当前持仓数据
	const currentPositions = ref([]);

	// 历史持仓数据
	const historyPositions = ref([]);
	// 跳转详情页面
	const goDetails = (item) => {
		if (item && item.id) {
			uni.navigateTo({
				url: `/pages/position/details?id=${item.id}`
			});
		} else {
			uni.showToast({
				title: '订单信息错误',
				icon: 'none'
			});
		}
	}
	
	// 页面加载时获取数据
	onMounted(() => {
		loadPositionData();
	});
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding-bottom: 100rpx;
		box-sizing: border-box;
		padding: 34.89rpx;
	}

	// 持仓类型切换
	.position-tabs {
		display: flex;
		justify-content: space-between;
		margin-bottom: 31.4rpx;
		border-radius: 27.91rpx;
		box-sizing: border-box;
		padding: 1px;
		background: linear-gradient(90deg, rgba(14, 194, 157, 1) 0%, rgba(88, 218, 221, 1) 35.42%, rgba(25, 162, 203, 1) 68.75%, rgba(2, 124, 217, 1) 100%);

		.border-box {
			width: 100%;
			display: flex;
			align-items: center;
			border-radius: 27.91rpx;
			background-color: #Fff;
			padding: 13.95rpx 34.89rpx;
		}

		.tab-item {
			width: 296.53rpx;
			height: 69.77rpx;
			opacity: 1;
			border-radius: 17.44rpx;
			text-align: center;
			transition: all 0.3s;
			line-height: 69.77rpx;
			font-size: 27.91rpx;
			font-weight: 500;
			color: rgba(102, 102, 102, 1);

			&.active {
				font-weight: 500;
				color: rgba(255, 255, 255, 1);
				background: linear-gradient(90deg, rgba(12, 193, 155, 1) 0%, rgba(91, 220, 222, 1) 34.03%, rgba(5, 145, 198, 1) 65.97%, rgba(2, 120, 220, 1) 100%);
			}
		}
	}

	// 持仓列表
	.position-list {
		// padding: 0 30rpx;

		.position-item {
			border-radius: 20.93rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
			margin-bottom: 20.93rpx;
			padding: 34.89rpx;

			.position-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20.93rpx;

				.symbol-info {
					display: flex;
					align-items: center;

					.symbol {
						font-size: 27.91rpx;
						font-weight: 500;
						// line-height: 40.42rpx;
						color: rgba(51, 51, 51, 1);
						margin-right: 10rpx;
					}

					.direction-tag {
						width: 30rpx;
						height: 30rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}



					.progress-time {
						font-size: 24rpx;
						color: #999999;
					}
				}

				.right {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.progress-bar {
						width: 143rpx;
						height: 6rpx;
						background: rgba(235, 235, 235, 1);
						border-radius: 1742.54rpx;

						.progress-fill {
							height: 100%;
							background: linear-gradient(90deg, rgba(22, 196, 163, 1) 0%, rgba(74, 214, 207, 1) 34.72%, rgba(18, 156, 202, 1) 65.97%, rgba(2, 123, 217, 1) 100%);
						}
					}

					.time-info {
						font-size: 24.42rpx;
						font-weight: 500;
						color: rgba(0, 0, 0, 1);
						margin-left: 22.68rpx;
					}
				}
			}

			.position-details {
				display: flex;
				justify-content: space-between;

				.detail-column {
					display: flex;
					flex-direction: column;
					text-align: center;

					.label {
						font-size: 27.91rpx;
						font-weight: 300;
						letter-spacing: 0rpx;
						line-height: 40.42rpx;
						color: rgba(0, 0, 0, 1);
						margin-bottom: 8rpx;
					}

					.value {
						font-size: 24.42rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						line-height: 35.36rpx;
						color: rgba(51, 51, 51, 1);

						&.profit {
							color: rgba(13, 179, 100, 1);
						}

						&.loss {
							color: rgba(247, 56, 79, 1);
						}

						&.ping {
							color: rgba(42, 130, 228, 1);
						}
						
						// 订单状态样式
						&.status {
							font-weight: 600;
							
							&.status-0 {
								color: rgba(255, 165, 0, 1); // 待结算 - 橙色
							}
							
							&.status-1 {
								color: rgba(13, 179, 100, 1); // 盈利 - 绿色
							}
							
							&.status-2 {
								color: rgba(247, 56, 79, 1); // 亏损 - 红色
							}
							
							&.status-3 {
								color: rgba(42, 130, 228, 1); // 平局 - 蓝色
							}
						}
					}
				}
			}



		}
	}

	// 加载状态
	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;

		.loading-text {
			font-size: 28rpx;
			color: rgba(153, 153, 153, 1);
		}
	}

	// 空数据状态
	.empty-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;

		.empty-text {
			font-size: 28rpx;
			color: rgba(153, 153, 153, 1);
		}
	}
</style>